//
//  SubRip.m
//  TextTracks
//
//  Created by Sebas on 06/11/07.
//  Copyright 2007 Sebas Corp. All rights reserved.
//

#import "SubRip.h"
#import "SubRipItem.h"


@implementation SubRip

-(id)init
{
	return [self initWithString:@""];
}

-(id)initWithString:(NSString *)aString
{
	if (( self = [super init]) != nil)
	{
		
		itemsCollection = [[NSMutableArray alloc] init];
		
		if([aString length] > 0)
		{
			NSArray* split = [aString componentsSeparatedByString:@"\r\n\r\n"];
			
			for(NSString* item in split)
			{
				NSArray* lines = [item componentsSeparatedByString:@"\r\n"];
				
				if([lines count] >= 3)
				{
					SubRipItem* srItem = [[SubRipItem alloc] initWithString:item ];
					[itemsCollection addObject:srItem];
				}
			}
		}
		
	}		
	
	
	return self;
	
}

-(void)adjustTime:(float)timeInSeconds
{
	for(SubRipItem *item  in itemsCollection)
	{
		item.startTime = [self addSeconds:timeInSeconds toStringTime:item.startTime];
		item.endTime = [self addSeconds:timeInSeconds toStringTime:item.endTime];
	}			
}

-(NSString *)addSeconds:(int)nSeconds toStringTime:(NSString *)aString
{
	NSMutableString* tmpTime;
	
	tmpTime = [NSMutableString stringWithString:aString];
	
	[tmpTime replaceOccurrencesOfString:@"," withString:@"." options:NSLiteralSearch range:NSMakeRange(0, [tmpTime length])];
	
	NSArray* timeItems = [tmpTime componentsSeparatedByString:@":"];
	if([timeItems count] == 3)
	{
		float seconds = [[NSNumber numberWithFloat: [[timeItems objectAtIndex:2] floatValue]] floatValue];
		int minutes = [[NSNumber numberWithInt: [[timeItems objectAtIndex:1] intValue]] intValue];
		int hours = [[NSNumber numberWithInt: [[timeItems objectAtIndex:0] intValue]] intValue];
		
		seconds = seconds + minutes * 60 + hours * 3600 + nSeconds;
		
		hours = seconds / 3600;
		minutes = (seconds / 3600 - hours) * 3600 / 60;
		seconds = seconds - hours * 3600 - minutes * 60;
	
		NSString *stringTime = [[NSString alloc] initWithFormat:@"%.2d:%.2d:%.3f",hours, minutes, seconds];
		
		tmpTime = [NSMutableString stringWithString:stringTime];
	
		[tmpTime replaceOccurrencesOfString:@"." withString:@"," options:NSLiteralSearch range:NSMakeRange(0, [tmpTime length])];
		
		return tmpTime; 
		
		
	}
	else
		return @"";
	
}

-(NSMutableArray *)itemsCollection
{
	return itemsCollection;
}

@end
